const app = getApp();

Page({
  data: {
    role: "",
    orderItem: {},
    bookList: [],
    showBookPicker: false,
    active: 0
  },
  onLoad: function (options) {
    this.setData({
      role: app.globalData.userInfo.role
    })
  },
  onChange(e) {
    this.setData({
      active: e.detail.index
    })
  },
  getData() {
    wx.$apis.getAccountBookEasy().then(res => {
      let bookList = res.data && res.data.map(item => {
        item.text = item.name
        return item
      })
      this.setData({
        bookList: bookList
      })
    })
  },
  bookPicker(item) {
    this.setData({
      orderItem: item.detail,
      showBookPicker: true
    })
  },
  onBookCancel() {
    this.setData({
      syncOrderItem: {},
      showBookPicker: false
    })
  },
  onBookConfirm(event) {
    const {
      value
    } = event.detail;
    let params = {
      accountBookId: value.id,
      financeName: this.data.orderItem.financeName,
      recordTime: wx.$dayjs().format("YYYY-MM-DD HH:mm:ss"),
      orderType: this.data.orderItem.orderType,
      orderId: this.data.orderItem.id,
      type: this.data.orderItem.type,
    }
    wx.showLoading({
					title: "正在同步"
			})
			wx.$apis.addAccountBookRecord(params).then(res => {
      this.setData({
        showBookPicker: false
      })
      wx.showToast({
        title: '同步完成！',
        icon: 'success',
        duration: 1500
      })
      this.onPullDownRefresh()
    })
  },
  onShow: function () {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      let selected = 3;
      if (app.globalData.userInfo.role == 2) {
        selected = 2;
      }
      this.getTabBar().setData({
        selected: selected
      })
    }
    this.getData()
  },
  onPullDownRefresh() {
    const payment_farmer = this.selectComponent('.payment_farmer');
    const payment_purchaser = this.selectComponent('.payment_purchaser');
    if (payment_farmer) {
      payment_farmer.onPullDownRefresh && payment_farmer.onPullDownRefresh()
    } else if (payment_purchaser) {
      payment_purchaser.onPullDownRefresh && payment_purchaser.onPullDownRefresh()
    }
  },
  onReachBottom() {
    const payment_farmer = this.selectComponent('.payment_farmer');
    const payment_purchaser = this.selectComponent('.payment_purchaser');
    if (payment_farmer) {
      payment_farmer.onReachBottom && payment_farmer.onReachBottom()
    } else if (payment_purchaser) {
      payment_purchaser.onReachBottom && payment_purchaser.onReachBottom()
    }
  }
});